package com.hjy.web.controller;

import com.hjy.common.RequestHolder;
import com.hjy.pojo.SysUser;
import com.hjy.service.SysUserService;
import com.hjy.util.MD5Util;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Map;

@Controller
public class LoginController {

    @Resource
    private SysUserService sysUserService;

    @RequestMapping(value = {"/","/login"})
    public String login(Model model){
        model.addAttribute("username","");
        model.addAttribute("error","");
        return "forward:/login.jsp";
    }

    @RequestMapping(value = "/dologin")
    public String doLogin(String username, String password, HttpServletRequest request, Map<String, Object> map, HttpSession session){
        SysUser sysUser=sysUserService.findSysUser(username);
        String errorMsg = "";
        String ret = request.getParameter("ret");

            if (StringUtils.isBlank(username)) {
                errorMsg = "用户名不可以为空";
            } else if (StringUtils.isBlank(password)) {
                errorMsg = "密码不可以为空";
            }  else if (!MD5Util.isMd5Hash(sysUser,password,username)) {
                errorMsg = "密码错误";
            }else if (sysUser == null) {
                errorMsg = "查询不到指定的用户";
            }else if (sysUser.getStatus() != 1) {
                errorMsg = "用户已被冻结，请联系管理员";
            } else {
                request.getSession().setAttribute("user", sysUser);
                if (StringUtils.isNotBlank(ret)) {
                    return ret;
                } else {
                    return "redirect:/admin"; //TODO
                }
            }
        request.setAttribute("error", errorMsg);
        request.setAttribute("username", username);
        if (StringUtils.isNotBlank(ret)) {
            request.setAttribute("ret", ret);
        }

        return "forward:/login.jsp";
    }

    @GetMapping(value = "/logout")
    public String logout(HttpServletRequest request){
        request.getSession().removeAttribute("user");
        return "forward:/login.jsp";
    }

    @RequestMapping("/noAuth")
    public String error(){
        return "noAuth";
    }

    @RequestMapping("/admin")
    public String admin(){
        return "admin";
    }
}
